package main.role;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import main.util.ArrayUtil;
import main.util.JdbcUtil;
import main.util.SqlConstants;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class NewRoleAuth {

	public Sheet sheet=null;
	public String module;
	public int start;
	public int end;
	public int roleIdRow=0;//第几行是roleID的行
	
	public String getModule() {
		return module;
	}

	public void setModule(String module) {
		this.module = module;
	}

	public NewRoleAuth(Sheet sheet, int start, int end, int roleIdRow) {
		super();
		this.sheet = sheet;
		this.start = start;
		this.end = end;
		this.roleIdRow = roleIdRow;
	}

	/*start-end 获取roleId的范围值*/
	public String getRoleSql(String authId,int startRow,int endRow){
		List<String> roles=new ArrayList<String>();
		Integer startCol=start;
		Integer endCol=end+1;
		for(;startCol<endCol;startCol++){
			String checkFlag=getRangeRowValue(startRow, endRow, startCol);
			if("".equals(checkFlag)){
				continue;
			}
			
			roles.add(SqlConstants.getColValue(sheet.getRow(roleIdRow), startCol));
		}
		
		return authrole(roles, authId);
	}
	
	/*获取固定列，row行 值的勾选情况，只要有一行勾选，就认为此范围勾选*/
	public String getRangeRowValue(int startRow,int endRow,int col){
		String checkFlag="";
		for(;startRow<endRow+1;startRow++){
			checkFlag=SqlConstants.getColValue(sheet.getRow(startRow),col);
			if("".equals(checkFlag)){
				continue;
			}else{
				break;
			}
		}
		return checkFlag;
	}
	
	private String authrole(List<String> roles,String authId){
		if(roles.size()<1){
			//System.out.println("...................没有勾选："+authId);
			return "";
		}
		
		String sql="INSERT INTO t_ucp_roleauth (roleId,moduleId,authId) VALUES ";
		//可能有多个角色
		for(int i=0;i<roles.size();i++){
			String role=roles.get(i);
			if(role!=null && !"".equals(role)){
				role="('"+role+"','"+module+"','"+authId+"')";
				roles.set(i, role);
			}
			
		}
		return sql+ArrayUtil.conectArray(roles, ",")+";\n";
	}
	
	public static String getAuthIdByParentId(String superCode,String authName,JdbcUtil db){
		List<Map<String,Object>> auths=db.queryForList("SELECT AUTHID authId from t_ucp_authelement WHERE SUPERCODE='"+superCode+"' "
										+ "AND AUTHNAME='"+authName+"'");
		if(auths.size()==0){
			System.out.println(".......authName，不存在："+authName+"，父节点："+superCode);
			return null;
		}else if(auths.size()>1){
			System.out.println(".......authName，重复："+authName+"，节点："+auths.toString());
			return null;
		}
		
		return auths.get(0).get("AUTHID").toString();
	}

}
